package com.oracle.coherence.patterns.security;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import java.util.Map;

/**
 * An implementation of a {@link LoginModule} that basically creates a copy
 * of whatever {@link Subject} is already in scope of the current Thread.
 * <p/>
 */
public class CurrentSubjectLoginModule implements LoginModule {

    private Subject subject;

    public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> stringMap, Map<String, ?> stringMap1) {
        this.subject = subject;
    }

    public boolean login() throws LoginException {
        return true;
    }

    public boolean commit() throws LoginException {
        Subject current = KrbSecurityHelper.getCurrentSubject();
        if (current != null) {
            this.subject.getPrincipals().addAll(current.getPrincipals());
            this.subject.getPrivateCredentials().addAll(current.getPrivateCredentials());
            this.subject.getPublicCredentials().addAll(current.getPublicCredentials());
        }
        return true;
    }

    public boolean abort() throws LoginException {
        subject = null;
        return true;
    }

    public boolean logout() throws LoginException {
        subject = null;
        return true;
    }

}
